package com.yujin.topic;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * JMS生产者 ---消息发布者
 * @author Administrator
 */
public class JMSProducer {
	
	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;
	private static final int SENDNUM = 10;
	
	public static void main(String[] args) {
		
		ConnectionFactory factory = null;
		Connection conn = null;
		Session session = null;
		Destination destination = null;
		MessageProducer messageProducer = null; //消息生产者
		
		factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKERURL);
		try {
			conn = factory.createConnection();
			conn.start();
			/**
			 * 是否添加事务
			 * <code>Session.AUTO_ACKNOWLEDGE</code>,
			 * <code>Session.CLIENT_ACKNOWLEDGE</code>, and
             * <code>Session.DUPS_OK_ACKNOWLEDGE</code>.
			 */
			session = conn.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
			destination = session.createTopic("firstTopic"); //创建消息发布者
			messageProducer = session.createProducer(destination); //创建消息生产者
			
			sendMessage(session,messageProducer);
			
			session.commit();
			
		} catch (JMSException e) {
			e.printStackTrace();
		}finally{
			if(null != conn){
				try {
					conn.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if(null != session){
				try {
					session.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if(null != null){
				try {
					messageProducer.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void sendMessage(Session session,MessageProducer messageProducer) throws JMSException{
		for(int i = 0; i < SENDNUM; i++){
			TextMessage message = session.createTextMessage("发送JMS消息"+i); //创建消息
			messageProducer.send(message); //发送消息
		}
	}
}
